package com.hcj.springcloud;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

/**
 * 垃圾回收demo
 *
 * @author huangcj
 * @date 2021-04-27 14:12
 */
public class GCDemo {
    public static void main(String[] args) throws InterruptedException {
        // strong reference
        String str = "hello";
        System.out.println("str = " + str);
        // soft reference 强引用， jdk
        SoftReference<Object> strSoftReference = new SoftReference<>("soft reference");
        System.out.println("strSoftReference = " + strSoftReference.get());
        // weak reference 弱引用
        WeakReference<Object> strWeakReference = new WeakReference<>("weak reference");
        System.out.println("strWeakReference = " + strWeakReference.get());
        // phantom reference 幽灵引用
        PhantomReference<Object> strPhantomReference = new PhantomReference<Object>("phantom reference", new ReferenceQueue<>());
        System.out.println("strPhantomReference = " + strPhantomReference.get());

        // 手动调用gc后
        System.gc();
        Thread.sleep(3000L);

        System.out.println("gc after str = " + str);
        System.out.println("gc after strSoftReference = " + strSoftReference.get());
        System.out.println("gc after strWeakReference = " + strWeakReference.get());
        System.out.println("gc after strPhantomReference = " + strPhantomReference.get());

    }
}
